#!/usr/bin/env bash
# This is a pre-commit hook that validates code formatting.
#
# Install this by running the script with an argument of "install",
# which installs a symlink to .git/hooks/precommit:
# $ ln -s ../../hooks/pre-commit .git/hooks/pre-commit

root="$(git rev-parse --show-toplevel 2>/dev/null)"

# Some sanity checking.
hash cargo || exit 1
[[ -n "$root" ]] || exit 1

# Installation.
if [[ "$1" == "install" ]]; then
    hook="$root"/.git/hooks/pre-commit
    if [[ ! -e "$hook" ]]; then
        ln -s ../../hooks/pre-commit "$hook"
        echo "Installed git pre-commit hook at $hook"
    else
        echo "Hook already installed"
    fi
    exit
fi

# Check formatting.
trap 'git stash pop -q' EXIT
git stash push -k -u -q -m "pre-commit stash"
cargo fmt -- --check -l
exit $?
